package cn.tedu.crm.operatelog.loggingaspect;

import cn.dev33.satoken.stp.StpUtil;
import cn.tedu.crm.base.response.StatusCode;
import cn.tedu.crm.operatelog.loggable.Loggable;
import cn.tedu.crm.operatelog.mapper.OperateLogMapper;
import cn.tedu.crm.operatelog.pojo.entity.OperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LoggingAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired(required = false)
    private HttpServletRequest request;

    @Around("@annotation(loggable)")
    public Object logOperation(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
        OperateLog log = new OperateLog();
        log.setOperateModel(loggable.module().getName());
        log.setOperateContent(loggable.type().getName());
        log.setOperateTime(new Date());

        // 获取当前用户（需要结合具体的安全框架）
        // 获取当前用户
        String name = null;
        Long userId = null;
        if (StpUtil.isLogin()) {  // 先判断是否登录
            name = StpUtil.getSession().getString("username");
            userId = StpUtil.getLoginIdAsLong();
        }
        log.setOperateName(name != null ? name : "匿名用户");
        log.setUserId(userId != null ? userId : -1L);
       /* String name = StpUtil.getSession().getString("username");
        Long userId = StpUtil.getLoginIdAsLong();
        if(name != null || userId != null){
            log.setOperateName(name);
            log.setUserId(userId);
        }*/
        // 获取IP地址
        log.setOperateIp(request != null ? getClientIp(request) : "N/A");

        /*// 获取方法参数详情
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            log.setOperationDetail("Parameters: " + Arrays.toString(args));
        }*/

        try {
            Object result = joinPoint.proceed();
            log.setOperateStatus("操作成功");
            return result;
        } catch (Exception e) {
            log.setOperateStatus("操作失败:"+ e.getMessage());
            throw e;
        } finally {
            operateLogMapper.saveLog(log);
        }
    }
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0];  // 取第一个IP
    }
}
